<template>
  <div class="box cartBox">
    <van-nav-bar title="购物车" left-arrow @click-left="onClickLeft">
      <template #right>
        <van-popover
          v-model="showPopover"
          trigger="click"
          :actions="actions"
          @select="onSelect"
          placement="bottom-end"
        >
          <template #reference>
            <van-icon name="ellipsis" size="18" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>
    <van-empty description="当前购物车为空,快去挑选几件宝贝" v-if="cartList.length<1">
      <van-button round type="danger" class="bottom-button" @click="$router.push('/home')">去挑选</van-button>
    </van-empty>
    <div class="cont" v-else>
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @edit="onEdit"
      />
      <div class="cartCont">
        <van-swipe-cell
          v-for="(item,idx) in cartList"
          :key="item.proId"
        >
          <van-card
            :price="item.price"
            class="goods-card"
          >
            <template #title>
              <router-link :to="'/detail/'+item.proId" tag="div" class="van-card__title van-multi-ellipsis--l2">
                {{item.proName}}
              </router-link>
            </template>
            <template #thumb>
              <van-checkbox v-model="item.flag" shape="square" @input="onSetFlag(idx)" />
              <router-link :to="'/detail/'+item.proId">
                <van-image
                  fit="contain"
                  :src="item.img"
                />
              </router-link>
            </template>
            <template #num>
              <van-stepper v-model="item.num" theme="round" button-size="22" disable-input @change="onSetNum(idx)" />
            </template>
          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="onDel(idx)" />
          </template>
        </van-swipe-cell>
      </div>
      <van-submit-bar :price="allPrice" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="allFlag">全选</van-checkbox>
      <template #tip>
        当前选中了<span class="allNum">{{allNum}}</span>件商品
      </template>
    </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { getCart, setFlag, setAllFlag, setNum, delCart, addOrder } from '@/api/request.js'
import Vue from 'vue'
import { NavBar, Popover, Icon, AddressList, Toast, SwipeCell, Card, Button, Checkbox, CheckboxGroup, Image as VanImage, Stepper, SubmitBar, Empty } from 'vant'

Vue.use(NavBar)
Vue.use(Popover)
Vue.use(Icon)
Vue.use(AddressList)
Vue.use(Toast)
Vue.use(SwipeCell)
Vue.use(Card)
Vue.use(Button)
Vue.use(Checkbox)
Vue.use(CheckboxGroup)
Vue.use(VanImage)
Vue.use(Stepper)
Vue.use(SubmitBar)
Vue.use(Empty)

export default {
  beforeRouteEnter (to, from, next) {
    if (sessionStorage.getItem('isLogin') === 'ok') {
      next()
    } else {
      next('/login?from=' + from.name)
    }
  },
  data () {
    return {
      showPopover: false,
      actions: [{ text: '首页', path: '/home' }, { text: '分类', path: '/kind' }, { text: '购物车' }, { text: '我的' }, { text: '搜索' }, { text: '分享' }],
      chosenAddressId: '1',
      list: [
        {
          id: '1',
          name: '张三',
          tel: '13000000000',
          address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
          isDefault: true
        }
      ],
      cartList: []
    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    onSelect (i) {
      this.$router.push(i.path)
    },
    onEdit (item, index) {
      Toast('编辑地址:' + index)
    },
    onSubmit () {
      const proData = []
      this.cartList.forEach(val => {
        if (val.flag) {
          proData.push({
            proId: val.proId,
            num: val.num
          })
        }
      })
      // 前端打包数据,直接发给后端(不推荐)
      // const proData = this.cartList.filter(val => val.flag)
      // console.log(proData)
      addOrder({
        userId: sessionStorage.getItem('userId'),
        proData: JSON.stringify(proData)
      }).then(data => {
        // console.log(data.data)
        this.$router.push('/order')
      })
    },
    onSetFlag (i) {
      setFlag({
        userId: sessionStorage.getItem('userId'),
        proId: this.cartList[i].proId,
        flag: this.cartList[i].flag ? 1 : 0
      }).then(data => {
        // console.log(data.data)
      }).catch(err => console.log(err))
    },
    onSetNum (i) {
      setNum({
        userId: sessionStorage.getItem('userId'),
        proId: this.cartList[i].proId,
        num: this.cartList[i].num
      }).then(data => {
        // console.log(data.data)
      })
    },
    onDel (i) {
      delCart({
        userId: sessionStorage.getItem('userId'),
        proId: this.cartList[i].proId
      }).then(data => {
        this.cartList = data.data.msg.proData
      })
    }
  },
  mounted () {
    getCart({
      userId: sessionStorage.getItem('userId')
    }).then(data => {
      this.cartList = data.data.msg.proData
    })
  },
  computed: {
    allFlag: {
      get () {
        return this.cartList.every(val => val.flag)
      },
      set (v) {
        setAllFlag({
          userId: sessionStorage.getItem('userId'),
          flag: v
        }).then(data => {
          console.log(data.data)
        })
        this.cartList.forEach(val => {
          val.flag = v
        })
      }
    },
    allPrice () {
      // 利用数组的归并方法,快速计算总价
      return this.cartList.reduce((start, val) => {
        if (val.flag) {
          return start + val.price * val.num * 100
        } else {
          return start
        }
      }, 0)
    },
    allNum () {
      return this.cartList.reduce((start, val) => {
        if (val.flag) {
          return start + val.num
        } else {
          return start
        }
      }, 0)
    }
  }
}
</script>

<style lang="scss">
.cartBox{
  display: flex;
  flex-direction: column;
  overflow: auto;
}
.cartCont{
  overflow: auto;
  flex: 1;
  padding-bottom: 1rem;
  .goods-card {
    margin: 0;
    background-color: white;
    .van-card__thumb{
      width: 1.1rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .van-checkbox{
        width: 0.2rem;
        height: 0.2rem;
      }
      .van-image{
        width: 0.8rem;
        height: 0.8rem;
      }
    }
  }
  .delete-button {
    height: 100%;
  }
}
.allNum{
  font-size: 0.3rem;
  font-weight: bold;
}
.van-address-list{
  height: 1rem;
  padding: 0 12px;
  .van-address-list__bottom{
    display: none;
  }
}
</style>
